package com.luuyi.actionchain;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;

import com.luuyi.actionchain.action.AsyncDelayAction;
import com.luuyi.actionchain.action.DialogAction;
import com.luuyi.actionchain.action.ToastAction;

public class ActiveAddActionsActivity extends AppCompatActivity {

    private ActionsAdapter actionsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_active_add_actions);

        RecyclerView rvActions = findViewById(R.id.rv_actions);
        rvActions.setLayoutManager(new LinearLayoutManager(this));
        actionsAdapter = new ActionsAdapter();
        rvActions.setAdapter(actionsAdapter);
        ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelperCallback());
        helper.attachToRecyclerView(rvActions);

        findViewById(R.id.tv_add_dialog).setOnClickListener(v -> actionsAdapter.addAction(new DialogAction(this)));
        findViewById(R.id.tv_add_sleep).setOnClickListener(v -> actionsAdapter.addAction(new AsyncDelayAction(this)));
        findViewById(R.id.tv_add_toast).setOnClickListener(v -> actionsAdapter.addAction(new ToastAction(this)));

        findViewById(R.id.tv_do_actions).setOnClickListener(v -> actionsAdapter.startFirstAction());
    }

    public class ItemTouchHelperCallback extends ItemTouchHelper.Callback {

        @Override
        public boolean isLongPressDragEnabled() {
            return super.isLongPressDragEnabled();
        }

        @Override
        public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
            final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            final int swipeFlags = ItemTouchHelper.LEFT;
            return makeMovementFlags(dragFlags, swipeFlags);
        }

        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder viewHolder1) {
            actionsAdapter.onItemMove(viewHolder.getAdapterPosition(), viewHolder1.getAdapterPosition());
            return false;
        }

        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
            actionsAdapter.removeItem(viewHolder.getAdapterPosition());
        }
    }
}